/* this module implements the dynamic memory allocation system (like malloc in C) */

#ifndef DYNAMIC_MEMORY_H
#define DYNAMIC_MEMORY_H

#include "null.h"
#include "types.h"

#define HEAP_LOWEST_ADDRESS 0x80700000
#define HEAP_HIGHEST_ADDRESS 0x80800000
#define HEAP_SIZE (HEAP_HIGHEST_ADDRESS - HEAP_LOWEST_ADDRESS)

#define STATUS_FREE 0
#define STATUS_USED 1

/* type definitions */

typedef struct _header{
  struct _header* next; //points to the next free space
  uint32_t size; //gives the size of a free space
  uint32_t status;
  int32_t allocated_by;
}header;


/* function definitions */

/* initializes the heap data structure to make it usable */
void initialize_heap();

/* allocates size bytes (+ sizeof(header)) on behalf of pid and returns a pointer to the allocated area. Returns NULL if out of memory */
void* malloc(int32_t size, int32_t pid);

/* free the area pointer by pointer. If pointer does not point to an area allocated by malloc, 0 is returned. Returns 1 otherwise. pointer must also have been allocated by the process pid otherwise, the function returns 0 and does not free anything   */
int32_t free(void* pointer, int32_t pid);

/* tests if pointer can be merged with prev and/or next and do it. */
void free_and_merge(header* pointer, header* prev, header* next);

/* sets the information of a header */
void set_header(header* pointer, uint32_t size, header* next, uint32_t status);

/* frees all the blocks owned by pid. Called to avoid memory leaks when a process terminates */
void free_all_pid(int32_t pid);

#endif
